package com.cheng.im.common.codec;

import com.cheng.im.common.constants.ProtoInstants;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.util.List;

public class ProtobufWebsocketEncoder extends MessageToMessageEncoder<ProtoMsgV1.Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ProtoMsgV1.Message msg, List<Object> out) throws Exception {
        byte[] bytes = msg.toByteArray();// 将对象转换为byte

        // 加密消息体
        /*ThreeDES des = channel.channel().attr(Constants.ENCRYPT).get();
        byte[] encryptByte = des.encrypt(bytes);*/
        int length = bytes.length;// 读取消息的长度

        ByteBuf byteBuf = Unpooled.directBuffer(8+length);
        byteBuf.writeShort(ProtoInstants.MAGIC_CODE);
        byteBuf.writeShort(ProtoInstants.VERSION_CODE);

        // 先将消息长度写入，也就是消息头
        byteBuf.writeInt(length);
        // 消息体中包含我们要发送的数据
        byteBuf.writeBytes(bytes);

        out.add(new BinaryWebSocketFrame(byteBuf));
    }
}
